package com.km.wskj.itmonitor.pager.wq.knowledgelib;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.Files;
import com.km.wskj.itmonitor.model.KnowledgeItem;
import com.km.wskj.itmonitor.model.NewsDetail;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.utils.CustomShareListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.control.UrlControl;
import com.zxl.zxlapplibrary.http.OkHttpUtils;
import com.zxl.zxlapplibrary.http.callback.StringCallback;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.util.WpsUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/3/9.
 */
//知识库详情页面
public class KnowledgeDetailActivity extends LActivity implements StateLayout.OnViewRefreshListener {
    private static final String TAG = "KnowledgeDetailActivity";

    //ui
    @BindView(R.id.tv_share)
    TextView mShare;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;
    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;

    //data
    private KnowledgeItem mKnowledgeList;
    private List<Files> files;
    private UMShareListener mShareListener;
    private ShareAction mShareAction;
    private String mWebUrl, mShareTitle;
    private MyAdapter mAdapter;
    private WebView mWebView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_knowledge_detail);
        ButterKnife.bind(this);

        if (getIntent().hasExtra("data"))
            mKnowledgeList = (KnowledgeItem) getIntent().getSerializableExtra("data");

        mWebUrl = UrlControl.url("knowledge/html") + "?id=" + mKnowledgeList.id;
        mShareTitle = mKnowledgeList.title;

        stateLayout.setRefreshListener(this);

        initView();
        initData();
    }

    private void initView() {
        mShareListener = new CustomShareListener(context);
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(context).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE
        )
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        UMWeb web = new UMWeb(mWebUrl);
                        web.setTitle(mShareTitle + "");
                        web.setDescription("智慧运维是专门为一些企业开发的，IT设施智能管理平台，涉及服务器、应用、网络、存储、虚拟化、日志等全部IT设施全面监控。 监控模块主要包括了：报警、应用系统、动环、服务器、数据库、中间件、存储、以太网、刀箱、虚拟化、安全、数据备份等监控");
                        web.setThumb(new UMImage(context, R.mipmap.logo));
                        new ShareAction(context).withMedia(web)
                                .setPlatform(share_media)
                                .setCallback(mShareListener)
                                .share();
                    }
                });
    }

    private void initData() {
        stateLayout.showLoadingView();
        pdc.knowledgeDetail(HTTP_TASK_TAG, mKnowledgeList.id, new ZxlGenericsCallback<NewsDetail>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(NewsDetail newsDetail, int i) {
                files = new ArrayList<>();
                files = newsDetail.files;

                initPullToRefresh();
            }
        });
    }

    private void initPullToRefresh() {
        //添加头布局
        View view = getLayoutInflater().inflate(R.layout.header_knowledge_detail, null);
        mWebView = (WebView) view.findViewById(R.id.webView);

        //请求HTML
        OkHttpUtils.get().url(UrlControl.url("knowledge/html"))
                .addParams("id", mKnowledgeList.id).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(String s, int i) {
                mWebView.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                stateLayout.showLoadingView();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                stateLayout.showContentView();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.d(TAG, "onReceivedError: " + errorCode + " : " + description + " : " + failingUrl);
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        mZrcListView.addHeaderView(view);

        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#eeeeee"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onFresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoad();
            }
        });
        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                Files item = (Files) parent.getItemAtPosition(position);
                String suffix = item.suffix;
                String fileUrl = item.host + item.file_path + item.new_file_name;
                if (suffix.equals(".docx")
                        || suffix.equals(".doc")
                        || suffix.equals(".pdf")
                        || suffix.equals(".pptx")
                        || suffix.equals(".ppt")
                        || suffix.equals(".xls")
                        || suffix.equals(".xlsx ")
                        || suffix.equals(".txt"))
                    WpsUtil.openDocInWps(context, fileUrl, item.original_file_name);
            }
        });
        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
    }

    //加载更多
    private void onLoad() {
        mAdapter.notifyDataSetChanged();
        mZrcListView.setRefreshSuccess();
    }

    //下啦刷新
    private void onFresh() {
        mAdapter.notifyDataSetChanged();
        mZrcListView.setRefreshSuccess();
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return files.size();
        }

        @Override
        public Object getItem(int i) {
            return files.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            BaseAdapterHelper mHelper = BaseAdapterHelper.get(context, view, viewGroup, R.layout.item_knowledge_detail);
            Files item = KnowledgeDetailActivity.this.files.get(i);
            mHelper.setText(R.id.tv_file, item.original_file_name);

            return mHelper.getView();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.tool_bar_back, R.id.tv_share})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tv_share:
                mShareAction.open();
                break;
        }
    }

//    @OnClick(R.id.tv_file_download)
//    public void file(View v) {
//        if (files.isEmpty())
//            return;
//
//        String suffix = files.get(0).suffix;
//        if (suffix.equals(".docx")
//                || suffix.equals(".doc")
//                || suffix.equals(".pdf")
//                || suffix.equals(".pptx")
//                || suffix.equals(".ppt")
//                || suffix.equals(".xls")
//                || suffix.equals(".xlsx "))
//            WpsUtil.openDocInWps(context, fileUrl, files.get(0).original_file_name);
//    }

    //加载出错点击重试
    @Override
    public void refreshClick() {
        initData();
    }

    @Override
    public void loginClick() {

    }
}
